package com.wwm.petadopt;

import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.etsy.android.grid.StaggeredGridView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


public class HomepageFragment extends Fragment implements AbsListView.OnScrollListener, AbsListView.OnItemClickListener, AdapterView.OnItemLongClickListener
{
	private static final String TAG = "StaggeredGridActivity";
	private StaggeredGridView mGridView;
	private boolean mHasRequestedMore;
	private SampleAdapter mAdapter;
	private static android.app.FragmentManager fragmentManager;
	private ArrayList<PetDetail> mData;
	private RequestQueue mRequestQueue;

    private  View view;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle saveInstanceState)
	{
		//View view = mFadingHelper.createView(inflater);

		 view = inflater.inflate(R.layout.fragment_homepage, container, false);
		fragmentManager=getActivity().getFragmentManager();

		mGridView = (StaggeredGridView) view.findViewById(R.id.grid_view);

		LayoutInflater layoutInflater = inflater;

		View header = layoutInflater.inflate(R.layout.list_item_header_footer, null);

		View footer = layoutInflater.inflate(R.layout.blank, null);
//		TextView txtHeaderTitle = (TextView) header.findViewById(R.id.txt_title);
//		TextView txtFooterTitle =  (TextView) footer.findViewById(R.id.txt_title);
//		txtHeaderTitle.setText("THE HEADER!");
//		txtFooterTitle.setText("THE FOOTER!");
//
		mGridView.addHeaderView(header);
		mGridView.addFooterView(footer);
		mAdapter = new SampleAdapter(container.getContext(), R.id.textview_firstline);

//		// do we have saved data?
//		if (savedInstanceState != null) {
//			mData = savedInstanceState.getStringArrayList(SAVED_DATA_KEY);
//		}

		mRequestQueue = Volley.newRequestQueue(view.getContext());
		Map<String, String> map = new HashMap<String, String>();
		map.put("RequestNum", "20");
		map.put("RequestNumType", "all");

		JsonObjectRequest jr = new JsonObjectRequest(Request.Method.POST, GlobalData.GET_PET_INFO_WITH_NUM_URL, new JSONObject(map), new Response.Listener<JSONObject>()
		{
			@Override
			public void onResponse(JSONObject response)
			{
				Log.i("petadopt", response.toString());
				//parseJSON(response);
				//petIDArray = new ArrayList<Integer>();
				ArrayList<PetDetail> petDetailArray = new ArrayList<PetDetail>();


				try {
					Iterator it = response.keys();
					while (it.hasNext()) {
						String key = (String) it.next();
						String value = response.getString(key);
						JSONObject j = response.getJSONObject(key);
						PetDetail p = new PetDetail(j);
						petDetailArray.add(p);
						//petIDArray.add(Integer.parseInt(value));
					}

					mData = petDetailArray;

//					if (mData == null) {
//						SampleData sampleData=new SampleData(mRequestQueue);
//						mData = sampleData.generateSampleData();
//					}

					for (PetDetail data : mData) {
						mAdapter.add(data);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}

			}
		}, new Response.ErrorListener()
		{
			@Override
			public void onErrorResponse(VolleyError error)
			{
				//Log.i("petadopt", error.getMessage());
			}
		});
		mRequestQueue.add(jr);




		mGridView.setAdapter(mAdapter);
		mGridView.setOnScrollListener(this);
		mGridView.setOnItemClickListener(this);
		mGridView.setOnItemLongClickListener(this);

		return view;
	}

	@Override
	public void onAttach(Activity activity)
	{
		super.onAttach(activity);



//		mFadingHelper = new FadingActionBarHelper()
//				.actionBarBackground(R.drawable.ab_background)
//				.headerLayout(R.layout.imageview_banner)
//				.contentLayout(R.layout.fragment_homepage);
//
//		mFadingHelper.initActionBar(activity);
	}

	@Override
	public void onScrollStateChanged(final AbsListView view, final int scrollState) {
		Log.d(TAG, "onScrollStateChanged:" + scrollState);
	}

	@Override
	public void onScroll(final AbsListView view, final int firstVisibleItem, final int visibleItemCount, final int totalItemCount) {
		Log.d(TAG, "onScroll firstVisibleItem:" + firstVisibleItem +
				" visibleItemCount:" + visibleItemCount +
				" totalItemCount:" + totalItemCount);
		// our handling
		if (!mHasRequestedMore) {
			int lastInScreen = firstVisibleItem + visibleItemCount;
			if (lastInScreen >= totalItemCount) {
				Log.d(TAG, "onScroll lastInScreen - so load more");
				mHasRequestedMore = false;
				//onLoadMoreItems();

			}
		}
	}


	@Override
	public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
		if(position!=0) {

			PetDetail petDetail = (PetDetail)adapterView.getItemAtPosition(position);

			Bundle bundle=new Bundle();
			bundle.putString("petId", petDetail.petId);

			Intent intent=new Intent("android.intent.action.PETDETAIL");
			intent.putExtras(bundle);
			startActivity(intent);
		}
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id)
	{

		return true;
	}

}
